package com.zjb.demo.common.controller;

import com.zjb.demo.common.config.AppConfig;
import com.zjb.demo.common.constant.ExceptionCode;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.common.domain.response.FileInfo;
import com.zjb.demo.common.exception.AppException;
import com.zjb.demo.common.util.FileUtils;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author 庄佳彬
 * @since 2023/12/23 23:07
 */
@Controller
@Mapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private static final String FILE_DELIMITERS = ",";

    @Inject
    private AppConfig appConfig;

    @Get
    @Mapping("/download")
    public DownloadedFile fileDownload(@Param(name = "fileName") String fileName) throws FileNotFoundException {
        if (!FileUtils.checkAllowDownload(fileName)) {
            throw new AppException(ExceptionCode.INVALID_FILE, fileName);
        }
        var filePath = appConfig.getLocalFilePath() + fileName;

        return new DownloadedFile(new File(filePath));
    }

    @Post
    @Mapping("/upload")
    public AjaxResult<FileInfo> uploadFile(UploadedFile file, Context ctx) throws IOException {
        var fileName = file.getName();
        var filePath = appConfig.getLocalFilePath() + fileName;
        file.transferTo(new File(filePath));
        var path = "/upload/" + fileName;//同配置项 solon.staticfiles.mappings[0].path
        return AjaxResult.success(new FileInfo(path, filePath));
    }
}
